<template>
  <view class="">
    <h1>WebSocket Chat</h1>
    <view class="">
      <form @submit="onSubmit">
        <input name="test" v-model="testValue"></input>
        <button form-type="submit">Submit</button>
      </form>
    </view>
  </view>
</template>

<script>
  import getSocket from "@/common/socket/index.js"
  import { refreshToken } from "@/common/api/index.js"
  
  const token = uni.getStorageSync('token')
  let socket = getSocket(token)

  export default {
    data() {
      return {
        testValue: null
      }
    },
    onShow() {
      this.socketInit()
    },
    onHide() {
      socket.disconnect();
    },
    onUnload() {
      socket.disconnect();
    },
    methods: {
      socketInit() {
        socket.connect()
        
        socket.on("connect", () => {
          console.log("connect", socket.id);
        });

        socket.on("disconnect", () => {
          console.log("disconnect", socket.id);
        });

        socket.on("connect_error", (message) => {
          console.log("connect_error", message);
        });

        socket.on("status", (data) => {
          if (data == 409) {
            socket.disconnect();
            refreshToken().then(res => {
              if (res.status == 200) {
                const token = res.data.access_token
                uni.setStorage('token', token)
                socket = getSocket(token)
                socket.connect()
              }
            })
          }
        });
      },
      onSubmit() {
        if (this.testValue) {
          socket.emit('message', this.testValue)
        }
      }
    },
  }
</script>

<style>
</style>
